﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace PizzaLunch
{
    public class TXSource : TweetSource
    {
        private const string DEFAULT_SHOW_TOPIC = "http://t.qq.com/p/t/";

        private const string STATUS_FRIENDS_TIMELINE = "statuses/home_timeline";
        private const string STATUS_USER_TIMELINE = "statuses/user_timeline";

        private const string USER_INFO = "user/info";
        private const string USER_OTHER_INFO = "user/other_info";

        private const string TOPIC_COMMENTS = "t/re_list";
        private const string TOPIC_ADD = "t/add";
        private const string TOPIC_RETWEET = "t/re_add";
        private const string TOPIC_COMMENT = "t/reply";
        private const string TOPIC_DELETE = "t/del";

        private const string FRIEND_FANSLIST = "friends/fanslist";
        private const string FRIEND_FRIENDSLIST = "friends/idollist";
        private const string FRIEND_USER_FANSLIST = "friends/user_fanslist";
        private const string FRIEND_USER_FRIENDSLIST = "friends/user_idollist";

        private static string TransferSex(string sex)
        {
            switch (sex)
            {
                case "1":
                    return "Male";
                case "2":
                    return "Femail";
                default:
                    return "Unknown";
            }
        }
        private static TweetItem.TweetItemType TransferType(string type)
        {
            switch (type)
            {
                case "1":
                    return TweetItem.TweetItemType.SOURCE;
                case "2":
                    return TweetItem.TweetItemType.RETWEET;
                case "4":
                    return TweetItem.TweetItemType.COMMENT;
                default:
                    return TweetItem.TweetItemType.ORIGIN;
            }
        }

        public override void CreateSetting()
        {
            if (string.IsNullOrEmpty(_sourceCfg.customKey))
                _sourceCfg.customKey = "27d1186230a443d1ac7f514a96376ada";
            if (string.IsNullOrEmpty(_sourceCfg.customSecrect))
                _sourceCfg.customSecrect = "eff11cc20a1d582b81f1affe3e754889";
            if (string.IsNullOrEmpty(_sourceCfg.callbackUrl))
                _sourceCfg.callbackUrl = "null";
            if (string.IsNullOrEmpty(_sourceCfg.baseUrl))
                _sourceCfg.baseUrl = "https://open.t.qq.com/cgi-bin/";
            if (string.IsNullOrEmpty(_sourceCfg.requestUrl))
                _sourceCfg.requestUrl = "http://open.t.qq.com/api/";
        }

        public TXSource()
            : base("TX")
        {
            ShowName = "TX";
            Logo = "Resource/TX16x16.png";
        }

        private void TransferUser(XmlNode node, UserInfo user)
        {
            user.ID = node["name"].InnerText;
            user.ShowName = node["nick"].InnerText;
            user.HeadUrl = node["head"].InnerText;
            if (string.IsNullOrEmpty(user.HeadUrl))
            {
                user.HeadUrl = "Resource/NoHead.jpg";
            }
            else
            {
                user.HeadUrl += @"/50";
            }
            if (node["isvip"].InnerText == "1")
                user.VIP = true;
            else
                user.VIP = false;
            user.Location = node["location"].InnerText;
            try
            {
                user.Birthday = new DateTime(Convert.ToInt32(node["birth_year"].InnerText),
                    Convert.ToInt32(node["birth_month"].InnerText),
                    Convert.ToInt32(node["birth_day"].InnerText));
                user.Gender = TransferSex(node["sex"].InnerText);
                user.Signature = node["introduction"].InnerText;
                user.friends = Convert.ToInt64(node["idolnum"].InnerText);
                user.follows = Convert.ToInt64(node["fansnum"].InnerText);
                user.topics = Convert.ToInt64(node["tweetnum"].InnerText);
            }
            catch
            {
                user.Birthday = new DateTime();
            }
        }

        private long TransferTweet(XmlNode node, TweetItem ti)
        {
            ti.ID = node["id"].InnerText;
            ti.Content = node["origtext"].InnerText;
            long timestamp = Convert.ToInt64(node["timestamp"].InnerText);
            ti.DateUpdate = Util.ConvertFromUnixTimestamp(timestamp);

            XmlNodeList imageList = node.SelectNodes("image");
            if (imageList!=null)
            {
                //foreach (XmlNode imgNode in imageList)
                ti.Image = imageList[0].InnerText;
                if (!string.IsNullOrEmpty(ti.Image))
                {
                    ti.HasImage = true;
                    ti.Thumbnail = ti.Image + @"/160";
                    ti.Image += @"/460";
                }
            }

            return timestamp;
        }

        public override string GetItemUrl(TweetItem ti)
        {
            string url = DEFAULT_SHOW_TOPIC + ti.ID;
            return url;
        }

        public override bool Query(TweetAccount tac)
        {
            List<Parameter> parameters = new List<Parameter>();
            oAuth.OauthKey oauthKey = new oAuth.OauthKey();
            oauthKey.customKey = SourceCfg.customKey;
            oauthKey.customSecrect = SourceCfg.customSecrect;
            oauthKey.tokenKey = tac.AccountCfg.accessKey;
            oauthKey.tokenSecrect = tac.AccountCfg.accessSecrect;

            parameters.Add(new Parameter("format", "xml"));
            parameters.Add(new Parameter("pagetime", tac.LastTimeStamp.ToString()));
            if (tac.LastTimeStamp == 0)
                parameters.Add(new Parameter("pageflag", "0"));
            else
                parameters.Add(new Parameter("pageflag", "2"));
            parameters.Add(new Parameter("reqnum", MainControl.GlobalSetting.REFRESH_ITEM_COUNT.ToString()));

            string queryString, retString;
            try
            {
                HttpRequest request = new HttpRequest();
                oAuth.GetOauthUrl(SourceCfg.requestUrl + STATUS_FRIENDS_TIMELINE, HttpRequest.HTTP_GET, oauthKey, parameters, out queryString);
                retString = request.HttpGet(SourceCfg.requestUrl + STATUS_FRIENDS_TIMELINE, queryString);
                if (string.IsNullOrEmpty(retString))
                    return false;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(retString);
                XmlNodeList nodeList = doc.FirstChild.SelectNodes("//info");
                if (nodeList != null)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        TweetItem ti = new TweetItem(tac, node.InnerXml);
                        UserInfo author = new UserInfo(tac);

                        ti.Type = TweetItem.TweetItemType.ORIGIN;
                        /*ti.ID = node["id"].InnerText;
                        long timestamp = Convert.ToInt64(node["timestamp"].InnerText);
                        if (timestamp > tac.LastTimeStamp)
                            tac.LastTimeStamp = timestamp;
                        ti.Content = node["origtext"].InnerText;
                        ti.DateUpdate = Util.ConvertFromUnixTimestamp(timestamp);

                        author.ID = node["name"].InnerText;
                        author.ShowName = node["nick"].InnerText;
                        author.HeadUrl = node["head"].InnerText;
                        if (node["isvip"].InnerText == "1")
                            author.VIP = true;
                        else
                            author.VIP = false;
                        author.Location = node["location"].InnerText;*/
                        TransferTweet(node, ti);
                        TransferUser(node, author);
                        MainControl.UpdateAllUser(author, ti);

                        if (node["source"] != null && !node["source"].IsEmpty)
                        {
                            UserInfo sourceAuthor = new UserInfo(tac);
                            ti.SourceItem = new TweetItem(tac, node["source"].InnerXml);

                            ti.SourceItem.Type = TweetItem.TweetItemType.SOURCE;
                            TransferTweet(node["source"], ti.SourceItem);
                            /*ti.SourceItem.ID = node["source"]["id"].InnerText;
                            ti.SourceItem.Content = node["source"]["origtext"].InnerText;
                            timestamp = Convert.ToInt64(node["source"]["timestamp"].InnerText);
                            ti.SourceItem.DateUpdate = Util.ConvertFromUnixTimestamp(timestamp);

                            sourceAuthor.ID = node["source"]["name"].InnerText;
                            sourceAuthor.ShowName = node["source"]["nick"].InnerText;
                            sourceAuthor.HeadUrl = node["source"]["head"].InnerText;
                            if (node["source"]["isvip"].InnerText == "1")
                                sourceAuthor.VIP = true;
                            else
                                sourceAuthor.VIP = false;
                            sourceAuthor.Location = node["source"]["location"].InnerText;*/

                            TransferUser(node["source"], sourceAuthor);
                            MainControl.UpdateAllUser(sourceAuthor, ti.SourceItem);
                        }
                        MainControl.UpdateTweets(ti);
                    }
                }
            }
            catch (Exception e)
            {
                MainControl.Logger.WriteLog(tac.Source.ShowName + " " + tac.AccountInfo.ShowName + " Query error with "
                    + e.ToString(), LoggerFile.LoggerLevel.LoggerError);
                return false;
            }

            return true;
        }

        public override void GetUserInfo(TweetAccount tac)
        {
            List<Parameter> parameters = new List<Parameter>();
            oAuth.OauthKey oauthKey = new oAuth.OauthKey();
            oauthKey.customKey = SourceCfg.customKey;
            oauthKey.customSecrect = SourceCfg.customSecrect;
            oauthKey.tokenKey = tac.AccountCfg.accessKey;
            oauthKey.tokenSecrect = tac.AccountCfg.accessSecrect;
            parameters.Add(new Parameter("format", "xml"));

            string queryString, retString;
            try
            {
                HttpRequest request = new HttpRequest();
                oAuth.GetOauthUrl(SourceCfg.requestUrl + USER_INFO, HttpRequest.HTTP_GET, oauthKey, parameters, out queryString);
                retString = request.HttpGet(SourceCfg.requestUrl + USER_INFO, queryString);
                if (string.IsNullOrEmpty(retString))
                    return;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(retString);
                if (doc["root"]!=null)
                    TransferUser(doc["root"]["data"], tac.AccountInfo);
                /*XmlNodeList nodeList = doc.FirstChild.SelectNodes("//data");
                if (nodeList != null)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        tac.ID = node["name"].InnerText;
                        tac.AccountInfo.ID = tac.ID;
                        tac.AccountInfo.ShowName = node["nick"].InnerText;
                        tac.AccountInfo.Location = node["location"].InnerText;
                        tac.AccountInfo.HeadUrl = node["head"].InnerText;
                        if (string.IsNullOrEmpty(tac.AccountInfo.HeadUrl))
                        {
                            tac.AccountInfo.HeadUrl = "Resource/NoHead.jpg";
                        }
                        else
                        {
                            tac.AccountInfo.HeadUrl += @"/30";
                        }
                        tac.AccountInfo.Gender = TransferSex(node["sex"].InnerText);
                        try
                        {
                            tac.AccountInfo.Birthday = new DateTime(Convert.ToInt32(node["birth_year"].InnerText),
                                Convert.ToInt32(node["birth_month"].InnerText),
                                Convert.ToInt32(node["birth_day"].InnerText));
                        }
                        catch
                        {
                            tac.AccountInfo.Birthday = new DateTime();
                        }
                        if (node["isvip"].InnerText == "1")
                            tac.AccountInfo.VIP = true;
                        else
                            tac.AccountInfo.VIP = false;
                        tac.AccountInfo.Signature = node["introduction"].InnerText;
                        tac.AccountInfo.friends = Convert.ToInt64(node["idolnum"].InnerText);
                        tac.AccountInfo.follows = Convert.ToInt64(node["fansnum"].InnerText);
                        tac.AccountInfo.topics = Convert.ToInt64(node["tweetnum"].InnerText);
                    }
                }*/
            }
            catch (Exception e)
            {
                MainControl.Logger.WriteLog(tac.Source.ShowName + " " + tac.AccountInfo.ShowName + " GetUserInfo error with "
                    + e.ToString(), LoggerFile.LoggerLevel.LoggerError);
            }
        }

        public override void GetUserInfoByID(TweetAccount tac, UserInfo user)
        {
            List<Parameter> parameters = new List<Parameter>();
            oAuth.OauthKey oauthKey = new oAuth.OauthKey();
            oauthKey.customKey = SourceCfg.customKey;
            oauthKey.customSecrect = SourceCfg.customSecrect;
            oauthKey.tokenKey = tac.AccountCfg.accessKey;
            oauthKey.tokenSecrect = tac.AccountCfg.accessSecrect;
            parameters.Add(new Parameter("format", "xml"));
            parameters.Add(new Parameter("name", user.GetID(tac)));

            string queryString, retString;
            try
            {
                HttpRequest request = new HttpRequest();
                oAuth.GetOauthUrl(SourceCfg.requestUrl + USER_OTHER_INFO, HttpRequest.HTTP_GET, oauthKey, parameters, out queryString);
                retString = request.HttpGet(SourceCfg.requestUrl + USER_OTHER_INFO, queryString);
                if (string.IsNullOrEmpty(retString))
                    return;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(retString);
                if (doc["root"] != null)
                    TransferUser(doc["root"]["data"], user);
                /*XmlNodeList nodeList = doc.FirstChild.SelectNodes("//data");
                if (nodeList != null)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        if (user.GetID(tac) != node["name"].InnerText)
                            continue;
                        user.ShowName = node["nick"].InnerText;
                        user.Location = node["location"].InnerText;
                        user.HeadUrl = node["head"].InnerText;
                        if (string.IsNullOrEmpty(user.HeadUrl))
                        {
                            user.HeadUrl = "Resource/NoHead.jpg";
                        }
                        else
                        {
                            user.HeadUrl += @"/30";
                        }
                        user.Gender = TransferSex(node["sex"].InnerText);
                        try
                        {
                            user.Birthday = new DateTime(Convert.ToInt32(node["birth_year"].InnerText),
                                Convert.ToInt32(node["birth_month"].InnerText),
                                Convert.ToInt32(node["birth_day"].InnerText));
                        }
                        catch
                        {
                            user.Birthday = new DateTime();
                        }
                        if (node["isvip"].InnerText == "1")
                            user.VIP = true;
                        else
                            user.VIP = false;
                        user.Signature = node["introduction"].InnerText;
                        user.friends = Convert.ToInt64(node["idolnum"].InnerText);
                        user.follows = Convert.ToInt64(node["fansnum"].InnerText);
                        user.topics = Convert.ToInt64(node["tweetnum"].InnerText);
                        user.Updated = true;
                    }
                }*/
            }
            catch (Exception e)
            {
                MainControl.Logger.WriteLog(tac.Source.ShowName + " " + tac.AccountInfo.ShowName + " GetUserInfoByID error with "
                    + e.ToString(), LoggerFile.LoggerLevel.LoggerError);
            }
        }

        public override void GetComments(TweetAccount tac, TweetItem ti)
        {
            List<Parameter> parameters = new List<Parameter>();
            oAuth.OauthKey oauthKey = new oAuth.OauthKey();
            oauthKey.customKey = SourceCfg.customKey;
            oauthKey.customSecrect = SourceCfg.customSecrect;
            oauthKey.tokenKey = tac.AccountCfg.accessKey;
            oauthKey.tokenSecrect = tac.AccountCfg.accessSecrect;

            parameters.Add(new Parameter("format", "xml"));
            parameters.Add(new Parameter("flag", "2"));
            if (ti.SourceItem != null)
                parameters.Add(new Parameter("rootid", ti.SourceItem.ID));
            else
                parameters.Add(new Parameter("rootid", ti.ID));
            if (ti.LastCommentTimeStamp == 0)
            {
                parameters.Add(new Parameter("pageflag", "0"));
                parameters.Add(new Parameter("twitterid", "0"));
            }
            else
            {
                parameters.Add(new Parameter("pageflag", "2"));
                parameters.Add(new Parameter("twitterid", ti.LastComment.ID));
            }
            parameters.Add(new Parameter("pagetime", ti.LastCommentTimeStamp.ToString()));
            parameters.Add(new Parameter("reqnum", MainControl.GlobalSetting.REFRESH_ITEM_COUNT.ToString()));
            //parameters.Add(new Parameter("twitterid", "0"));

            string queryString, retString;
            try
            {
                HttpRequest request = new HttpRequest();
                oAuth.GetOauthUrl(SourceCfg.requestUrl + TOPIC_COMMENTS, HttpRequest.HTTP_GET, oauthKey, parameters, out queryString);
                retString = request.HttpGet(SourceCfg.requestUrl + TOPIC_COMMENTS, queryString);
                if (string.IsNullOrEmpty(retString))
                    return;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(retString);
                XmlNodeList nodeList = doc.FirstChild.SelectNodes("//data/info");
                if (nodeList != null)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        TweetItem tiComment = new TweetItem(tac, node.InnerXml);
                        UserInfo author = new UserInfo(tac);

                        /*tiComment.Type = TransferType(node["type"].InnerText);
                        tiComment.ID = node["id"].InnerText;
                        long timestamp = Convert.ToInt64(node["timestamp"].InnerText);
                        if (timestamp > ti.LastCommentTimeStamp)
                        {
                            ti.LastComment = tiComment;
                            ti.LastCommentTimeStamp = timestamp;
                        }
                        tiComment.Content = node["origtext"].InnerText;
                        tiComment.DateUpdate = Util.ConvertFromUnixTimestamp(timestamp);

                        author.ID = node["name"].InnerText;
                        author.ShowName = node["nick"].InnerText;
                        author.HeadUrl = node["head"].InnerText;
                        if (node["isvip"].InnerText == "1")
                            author.VIP = true;
                        else
                            author.VIP = false;
                        author.Location = node["location"].InnerText;*/
                        TransferTweet(node, tiComment);
                        TransferUser(node, author);
                        MainControl.UpdateAllUser(author, tiComment);
                        MainControl.UpdateComments(ti, tiComment);
                    }
                }
            }
            catch (Exception e)
            {
                MainControl.Logger.WriteLog(tac.Source.ShowName + " " + tac.AccountInfo.ShowName + "GetComments error with " + ti.ID + " "
                    + e.ToString(), LoggerFile.LoggerLevel.LoggerError);
            }
        }
        public override bool Compose(TweetAccount tac, string content)
        {
            List<Parameter> parameters = new List<Parameter>();
            oAuth.OauthKey oauthKey = new oAuth.OauthKey();
            oauthKey.customKey = SourceCfg.customKey;
            oauthKey.customSecrect = SourceCfg.customSecrect;
            oauthKey.tokenKey = tac.AccountCfg.accessKey;
            oauthKey.tokenSecrect = tac.AccountCfg.accessSecrect;

            parameters.Add(new Parameter("format", "xml"));
            parameters.Add(new Parameter("clientip", System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString()));
            UTF8Encoding utf8 = new UTF8Encoding();
            Byte[] encodedBytes = utf8.GetBytes(content);
            parameters.Add(new Parameter("content", utf8.GetString(encodedBytes)));

            string queryString, retString;
            try
            {
                HttpRequest request = new HttpRequest();
                oAuth.GetOauthUrl(SourceCfg.requestUrl + TOPIC_ADD, HttpRequest.HTTP_POST, oauthKey, parameters, out queryString);
                retString = request.HttpPost(SourceCfg.requestUrl + TOPIC_ADD, queryString);
                if (string.IsNullOrEmpty(retString))
                    return false;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(retString);
                if (doc.FirstChild["ret"].InnerText == "0")
                {
                    return true;
                }
                else
                {
                    System.Windows.MessageBox.Show("Send Error");
                    return false;
                }
            }
            catch (Exception e)
            {
                MainControl.Logger.WriteLog(tac.Source.ShowName + " " + tac.AccountInfo.ShowName + "Compose error with "
                    + e.ToString(), LoggerFile.LoggerLevel.LoggerError);
                return false;
            }
        }

        public override bool Retweet(TweetAccount tac, TweetItem ti, string Content)
        {
            List<Parameter> parameters = new List<Parameter>();
            oAuth.OauthKey oauthKey = new oAuth.OauthKey();
            oauthKey.customKey = SourceCfg.customKey;
            oauthKey.customSecrect = SourceCfg.customSecrect;
            oauthKey.tokenKey = tac.AccountCfg.accessKey;
            oauthKey.tokenSecrect = tac.AccountCfg.accessSecrect;

            parameters.Add(new Parameter("format", "xml"));
            parameters.Add(new Parameter("clientip", System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString()));
            UTF8Encoding utf8 = new UTF8Encoding();
            Byte[] encodedBytes = utf8.GetBytes(Content);
            parameters.Add(new Parameter("content", utf8.GetString(encodedBytes)));
            if (ti.SourceItem != null)
                parameters.Add(new Parameter("reid", ti.SourceItem.ID));
            else
                parameters.Add(new Parameter("reid", ti.ID));

            string queryString, retString;
            try
            {
                HttpRequest request = new HttpRequest();
                oAuth.GetOauthUrl(SourceCfg.requestUrl + TOPIC_RETWEET, HttpRequest.HTTP_POST, oauthKey, parameters, out queryString);
                retString = request.HttpPost(SourceCfg.requestUrl + TOPIC_RETWEET, queryString);
                if (string.IsNullOrEmpty(retString))
                    return false;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(retString);
                if (doc.FirstChild["ret"].InnerText == "0")
                {
                    return true;
                }
                else
                {
                    System.Windows.MessageBox.Show("Send Error");
                    return false;
                }
            }
            catch (Exception e)
            {
                MainControl.Logger.WriteLog(tac.Source.ShowName + " " + tac.AccountInfo.ShowName + "Compose error with "
                    + e.ToString(), LoggerFile.LoggerLevel.LoggerError);
                return false;
            }
        }

        public override bool Comment(TweetAccount tac, TweetItem ti, string Content)
        {
            List<Parameter> parameters = new List<Parameter>();
            oAuth.OauthKey oauthKey = new oAuth.OauthKey();
            oauthKey.customKey = SourceCfg.customKey;
            oauthKey.customSecrect = SourceCfg.customSecrect;
            oauthKey.tokenKey = tac.AccountCfg.accessKey;
            oauthKey.tokenSecrect = tac.AccountCfg.accessSecrect;

            parameters.Add(new Parameter("format", "xml"));
            parameters.Add(new Parameter("clientip", System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString()));
            UTF8Encoding utf8 = new UTF8Encoding();
            Byte[] encodedBytes = utf8.GetBytes(Content);
            parameters.Add(new Parameter("content", utf8.GetString(encodedBytes)));
            if (ti.SourceItem != null)
                parameters.Add(new Parameter("reid", ti.SourceItem.ID));
            else
                parameters.Add(new Parameter("reid", ti.ID));

            string queryString, retString;
            try
            {
                HttpRequest request = new HttpRequest();
                oAuth.GetOauthUrl(SourceCfg.requestUrl + TOPIC_COMMENT, HttpRequest.HTTP_POST, oauthKey, parameters, out queryString);
                retString = request.HttpPost(SourceCfg.requestUrl + TOPIC_COMMENT, queryString);
                if (string.IsNullOrEmpty(retString))
                    return false;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(retString);
                if (doc.FirstChild["ret"].InnerText == "0")
                {
                    return true;
                }
                else
                {
                    System.Windows.MessageBox.Show("Send Error");
                    return false;
                }
            }
            catch (Exception e)
            {
                MainControl.Logger.WriteLog(tac.Source.ShowName + " " + tac.AccountInfo.ShowName + "Compose error with "
                    + e.ToString(), LoggerFile.LoggerLevel.LoggerError);
                return false;
            }
        }

        public override void GetFansList(TweetAccount tac, UserInfo userInfo, UserInfo.UserType uType, int index)
        {
            List<Parameter> parameters = new List<Parameter>();
            oAuth.OauthKey oauthKey = new oAuth.OauthKey();
            oauthKey.customKey = SourceCfg.customKey;
            oauthKey.customSecrect = SourceCfg.customSecrect;
            oauthKey.tokenKey = tac.AccountCfg.accessKey;
            oauthKey.tokenSecrect = tac.AccountCfg.accessSecrect;

            parameters.Add(new Parameter("format", "xml"));
            parameters.Add(new Parameter("reqnum", MainControl.GlobalSetting.REFRESH_ITEM_COUNT.ToString()));
            parameters.Add(new Parameter("startindex", index.ToString()));
            if (userInfo.GetType()!=MainControl.me.GetType())
                parameters.Add(new Parameter("name", userInfo.GetID(tac)));

            string queryString, retString;
            try
            {
                HttpRequest request = new HttpRequest();
                string requestUrl;
                if (userInfo.GetType() == MainControl.me.GetType())
                {
                    if (uType == UserInfo.UserType.USER_FANS)
                        requestUrl = SourceCfg.requestUrl + FRIEND_FANSLIST;
                    else
                        requestUrl = SourceCfg.requestUrl + FRIEND_FRIENDSLIST;
                }
                else
                {
                    if (uType == UserInfo.UserType.USER_FANS)
                        requestUrl = SourceCfg.requestUrl + FRIEND_USER_FANSLIST;
                    else
                        requestUrl = SourceCfg.requestUrl + FRIEND_USER_FRIENDSLIST;
                }
                oAuth.GetOauthUrl(requestUrl, HttpRequest.HTTP_GET, oauthKey, parameters, out queryString);
                retString = request.HttpGet(requestUrl, queryString);
                if (!string.IsNullOrEmpty(retString))
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(retString);
                    if (doc["root"] != null && doc["root"]["data"] != null)
                    {
                        XmlNodeList nodeList = doc.FirstChild.SelectNodes("//data/info");
                        if (nodeList != null)
                        {
                            foreach (XmlNode node in nodeList)
                            {
                                UserInfo fans = new UserInfo(tac);

                                /*fans.ID = node["name"].InnerText;
                                fans.ShowName = node["nick"].InnerText;
                                fans.Location = node["location"].InnerText;
                                fans.HeadUrl = node["head"].InnerText;
                                if (string.IsNullOrEmpty(fans.HeadUrl))
                                {
                                    fans.HeadUrl = "Resource/NoHead.jpg";
                                }
                                else
                                {
                                    fans.HeadUrl += @"/40";
                                }
                                if (node["isvip"].InnerText == "1")
                                    fans.VIP = true;
                                else
                                    fans.VIP = false;
                                fans.friends = Convert.ToInt64(node["idolnum"].InnerText);
                                fans.follows = Convert.ToInt64(node["fansnum"].InnerText);*/

                                TransferUser(node, fans);
                                MainControl.UpdateFans(userInfo, fans, uType);
                            }
                        }
                        if (doc["root"]["data"]["hasnext"].InnerText == "0")
                        {
                            if (uType == UserInfo.UserType.USER_FANS)
                            {
                                index += MainControl.GlobalSetting.REFRESH_ITEM_COUNT;
                                MainControl.AddQueryFansJob(tac, userInfo, index);
                            }
                            else
                            {
                                index += MainControl.GlobalSetting.REFRESH_ITEM_COUNT;
                                MainControl.AddQueryFriendsJob(tac, userInfo, index);
                            }
                        }
                        else
                        {
                            if (uType == UserInfo.UserType.USER_FANS)
                            {
                                userInfo[tac].FansCompleted = true;
                            }
                            else
                            {
                                userInfo[tac].FriendsCompleted = true;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MainControl.Logger.WriteLog(userInfo.Account.Source.ShowName + " " + userInfo.ShowName + "GetFans error with "
                    + e.ToString(), LoggerFile.LoggerLevel.LoggerError);
            }
        }

        public override bool QueryUserTimeline(TweetAccount tac, UserInfo user)
        {
            List<Parameter> parameters = new List<Parameter>();
            oAuth.OauthKey oauthKey = new oAuth.OauthKey();
            oauthKey.customKey = SourceCfg.customKey;
            oauthKey.customSecrect = SourceCfg.customSecrect;
            oauthKey.tokenKey = tac.AccountCfg.accessKey;
            oauthKey.tokenSecrect = tac.AccountCfg.accessSecrect;

            parameters.Add(new Parameter("format", "xml"));
            parameters.Add(new Parameter("pagetime", user[tac].LastComposeStamp.ToString()));
            if (user[tac].LastComposeStamp == 0)
                parameters.Add(new Parameter("pageflag", "0"));
            else
                parameters.Add(new Parameter("pageflag", "2"));
            parameters.Add(new Parameter("lastid", user[tac].LastComposeID));
            parameters.Add(new Parameter("name", user.GetID(tac)));
            //parameters.Add(new Parameter("reqnum", "5"));
            parameters.Add(new Parameter("reqnum", MainControl.GlobalSetting.REFRESH_ITEM_COUNT.ToString()));

            string queryString, retString;
            try
            {
                HttpRequest request = new HttpRequest();
                oAuth.GetOauthUrl(SourceCfg.requestUrl + STATUS_USER_TIMELINE, HttpRequest.HTTP_GET, oauthKey, parameters, out queryString);
                retString = request.HttpGet(SourceCfg.requestUrl + STATUS_USER_TIMELINE, queryString);
                if (string.IsNullOrEmpty(retString))
                    return false;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(retString);
                XmlNodeList nodeList = doc.FirstChild.SelectNodes("//info");
                if (nodeList != null)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        TweetItem ti = new TweetItem(tac, node.InnerXml);
                        UserInfo author = new UserInfo(tac);

                        /*ti.Type = TweetItem.TweetItemType.ORIGIN;
                        ti.ID = node["id"].InnerText;
                        long timestamp = Convert.ToInt64(node["timestamp"].InnerText);
                        if (timestamp > user[tac].LastComposeStamp)
                            user[tac].LastComposeStamp = timestamp;
                        ti.Content = node["origtext"].InnerText;
                        ti.DateUpdate = Util.ConvertFromUnixTimestamp(timestamp);

                        author.ID = node["name"].InnerText;
                        author.ShowName = node["nick"].InnerText;
                        author.HeadUrl = node["head"].InnerText;
                        if (node["isvip"].InnerText == "1")
                            author.VIP = true;
                        else
                            author.VIP = false;
                        author.Location = node["location"].InnerText;*/
                        TransferTweet(node, ti);
                        TransferUser(node, author);
                        MainControl.UpdateAllUser(author, ti);

                        if (node["source"] != null && !node["source"].IsEmpty)
                        {
                            UserInfo sourceAuthor = new UserInfo(tac);
                            ti.SourceItem = new TweetItem(tac, node["source"].InnerXml);
                            ti.SourceItem.Type = TweetItem.TweetItemType.SOURCE;

                            /*ti.SourceItem.ID = node["source"]["id"].InnerText;
                            ti.SourceItem.Content = node["source"]["origtext"].InnerText;
                            timestamp = Convert.ToInt64(node["source"]["timestamp"].InnerText);
                            ti.SourceItem.DateUpdate = Util.ConvertFromUnixTimestamp(timestamp);

                            sourceAuthor.ID = node["source"]["name"].InnerText;
                            sourceAuthor.ShowName = node["source"]["nick"].InnerText;
                            sourceAuthor.HeadUrl = node["source"]["head"].InnerText;
                            if (node["source"]["isvip"].InnerText == "1")
                                sourceAuthor.VIP = true;
                            else
                                sourceAuthor.VIP = false;
                            sourceAuthor.Location = node["source"]["location"].InnerText;*/
                            TransferTweet(node["source"], ti.SourceItem);
                            TransferUser(node["source"], sourceAuthor);
                            MainControl.UpdateAllUser(sourceAuthor, ti.SourceItem);
                        }
                        MainControl.UpdateUserTimeline(user, ti);
                    }
                }
            }
            catch (Exception e)
            {
                MainControl.Logger.WriteLog(tac.Source.ShowName + " " + tac.AccountInfo.ShowName + " Query error with "
                    + e.ToString(), LoggerFile.LoggerLevel.LoggerError);
                return false;
            }

            return true;
        }

        public override bool DeleteTweet(TweetAccount tac, TweetItem ti)
        {
            List<Parameter> parameters = new List<Parameter>();
            oAuth.OauthKey oauthKey = new oAuth.OauthKey();
            oauthKey.customKey = SourceCfg.customKey;
            oauthKey.customSecrect = SourceCfg.customSecrect;
            oauthKey.tokenKey = tac.AccountCfg.accessKey;
            oauthKey.tokenSecrect = tac.AccountCfg.accessSecrect;

            parameters.Add(new Parameter("format", "xml"));
            parameters.Add(new Parameter("id", ti.ID.ToString()));

            string queryString, retString;
            try
            {
                HttpRequest request = new HttpRequest();
                oAuth.GetOauthUrl(SourceCfg.requestUrl + TOPIC_DELETE, HttpRequest.HTTP_POST, oauthKey, parameters, out queryString);
                retString = request.HttpPost(SourceCfg.requestUrl + TOPIC_DELETE, queryString);
                if (string.IsNullOrEmpty(retString))
                    return false;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(retString);
                if (doc["root"] != null && doc["root"]["ret"] != null && doc["root"]["ret"].InnerText == "0")
                {
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                MainControl.Logger.WriteLog(tac.Source.ShowName + " " + tac.AccountInfo.ShowName + " Delete tweet error with "
                    + ti.ID.ToString() + e.ToString(), LoggerFile.LoggerLevel.LoggerError);
                return false;
            }
        }
    }
}
